<?php

/**
 * 库存转换
 */

namespace app\admin\logic\Inventory;

use app\admin\model\Inventory as InventoryModel;
use app\admin\model\Inventory;
use app\admin\model\LogisticsOrderItem;
use app\admin\model\ProductPrice as ProductPriceModel;
use app\admin\model\ProductDiscount as ProductDiscountModel;
use app\admin\model\OrderItem;
use app\admin\model\WholesalOrderItem;
use app\admin\model\Warehouse as WarehouseModel;
use app\common\service\Inventory as CommonInventoryService;
use app\common\service\Mail;
use app\admin\model\OrderItem as OrderItemModel;
use think\facade\Db;
use think\facade\Log;
use Exception;


class InventoryTransSave
{

    /**
     * @describe 获取库存相关订单列表
     * @author: Bobo
     * @date: 2025-08-26 19:24:26 
     * @param $param
     * @return array
     */
    public function getOrderByInventory($param)
    {
        // 查询库存信息
        $where = [['is_del', '=', '0'], ['id', '=', $param['id']]];
        // 获取库存基本信息
        $oInventoryModel = InventoryModel::with(['get_cname', 'get_creator_name', 'get_update_name'])->append(['is_futures_value', 'warehouse_value'])->where($where)->find();
        if (!$oInventoryModel) {
            return ['code' => 1, 'message' => '未找到库存信息！'];
        }

        $order_data = [];

        $wid_arr = [];
        if (isset($param['currentWId']) && $param['currentWId']) { // 当前仓库
            if (strpos($param['currentWId'], ',') !== false) {
                $wid_arr = explode(',', $param['currentWId']);
            } else {
                $wid_arr[] = $param['currentWId'];
            }
        }
        if (isset($param['transferInWId']) && $param['transferInWId']) { // 转入仓库
            $wid_arr[] = $param['transferInWId'];
        }
        $order_where = [
            ['product_id', '=', $oInventoryModel->productid],
            ['arrival_date', '=', $oInventoryModel->arrival_date],
            ['item.is_futures', '=', $oInventoryModel->is_futures],
            ['warehouse_id', 'in', $wid_arr],
            ['item.is_del', '=', 0],
            ['item.quantity', '>', 0],
            ['item.pending_quantity', '>', 0],
            ['o.pay_status', 'in', [3, 4]],
            ['o.review_node', '!=', 1]
        ];


        // 定义公共查询条件和字段
        $commonFields = [
            'GROUP_CONCAT( item.id ) as order_item_ids',
            'item.product_id',
            'item.arrival_date',
            'item.is_futures',
            'item.warehouse_id',
            'item.original_price',
            'item.actual_price',
            'SUM(item.quantity) as num',
            'o.id as order_id',
            'o.order_no',
            'o.order_category',
            'o.create_time',
            'o.pay_status',
            'o.total_amount',
            'c.cusname as username',
            'w.name as warehouse_name',
            'p.cname as product_name'
        ];
        $commonGroupBy = 'item.product_id, item.arrival_date, item.is_futures, item.warehouse_id, item.original_price, item.actual_price';

        // 查询普通订单
        $order_data = Db::table('db_order_item')
            ->alias('item')
            ->leftJoin('db_order o', 'o.id = item.order_id')
            ->leftJoin('db_customer c', 'o.user_id = c.id')
            ->leftJoin('db_warehouse w', 'item.warehouse_id = w.id')
            ->leftJoin('db_product p', 'p.id = item.product_id')
            ->where('o.order_type', '<>', '2')
            ->where($order_where)
            ->field($commonFields)
            ->group($commonGroupBy . ',o.id,o.order_no,o.order_category,o.create_time,o.pay_status,o.total_amount')
            ->select()
            ->map(function ($item) {
                return [
                    'order_item_ids' => $item['order_item_ids'] ?? null,
                    'order_id' => $item['order_id'] ?? null,
                    'order_no' => $item['order_no'] ?? '',
                    'create_time' => $item['create_time'] ?? '',
                    'username' => $item['username'] ?? '',
                    'total_amount' => $item['total_amount'] ?? 0,
                    'pay_status' => InventoryModel::getStaticEnum()['pay_status'][$item['pay_status']] ?? '',
                    'warehouse_name' => $item['warehouse_name'] ?? '',
                    'product_name' => $item['product_name'] ?? '',
                    'num' => $item['num'] ?? 0,
                    'is_futures' => InventoryModel::getStaticEnum()['is_futures'][$item['is_futures']] ?? '',
                    'original_price' => $item['original_price'] ?? null,
                    'actual_price' => $item['actual_price'] ?? null,
                    'order_type' => $item['order_category'],
                    'type' => $item['order_category'] == 'order' ? '1' : '2',
                    'arrival_date' => $item['arrival_date'] ?? '',
                    'warehouse_id' => $item['warehouse_id'] ?? '',
                    'is_futures_value' => $item['is_futures'] ?? '',
                    'product_id' => $item['product_id'] ?? '',
                ];
            })
            ->toArray();

        return ['code' => 0, 'message' => 'success', 'data' => $order_data];
    }


    public function transSaveByOrder($param)
    {
        $oOrderItemModel = OrderItemModel::where('is_futures', '<>', 0)->find($param['id']);
        if (!$oOrderItemModel) {
            return ['code' => 1, 'message' => '未找到订单信息！'];
        }

        // 计算需要转换的总数量
        $need_trans_quantity = array_sum(array_column($param['list'], 'quantity'));
        // 查询可转换数量
        $where = [
            ['productid', '=', $param['productid']],
            ['arrival_date', '=', null],
            ['is_futures', '=', 0],
            ['is_del', '=', 0],
            ['id', 'in', array_column($param['list'], 'id')]
        ];
        $warehouse = WarehouseModel::where('id', '=', $param['wid'])->field('fl_warehouse_id')->find();
        if ($warehouse['fl_warehouse_id'] != null) {
            $where[] = ['wid', '=', $param['wid']];
        } else {
            $warehouse_ids = WarehouseModel::where('fl_warehouse_id', '=', $param['wid'])->column('id');
            $where[] = ['wid', 'in', $warehouse_ids];
        }
        $InventoryArr = InventoryModel::where($where)
            ->whereRaw('(available_qty - lock_qty) > ?', [0])
            ->field([
                'available_qty - lock_qty as available_qty',
                'id',
                'purchase_currency',
                'purchase_price',
                'wid'
            ])
            ->select()
            ->toArray();
        $InventoryArr = array_column($InventoryArr, null, 'id');
        $inventoryService = new CommonInventoryService();

        Db::startTrans();
        try {


            $newOrderItemModel = new OrderItemModel();
            foreach ($param['list'] as $jer) {
                $inventory = $InventoryArr[$jer['id']];
                if ($inventory['available_qty'] < $jer['quantity']) {
                    throw new Exception('库存不足');
                } else {
                    $resultUpdateOrderItem = $newOrderItemModel
                        ->where('id', $param['id'])
                        ->bind([
                            'dec_num1' => intval($jer['quantity']),
                            'dec_num2' => intval($jer['quantity'])
                        ])
                        ->update([
                            'quantity' => Db::raw('quantity - :dec_num1'),
                            'pending_quantity' => Db::raw('pending_quantity - :dec_num2'),
                            'exceptionstatus' => Db::raw('CASE WHEN exceptionstatus = "4" THEN NULL ELSE exceptionstatus END'),
                        ]);

                    if (!$resultUpdateOrderItem) {
                        throw new Exception('订单转换原始明细数据扣减失败');
                    }

                    $resultInsert = $newOrderItemModel->insert([
                        'user_id' => $oOrderItemModel->user_id,
                        'order_id' => $oOrderItemModel->order_id,
                        'product_id' => $oOrderItemModel->product_id,
                        'warehouse_id' => $inventory['wid'],
                        'original_price' => $oOrderItemModel->original_price,
                        'actual_price' => $oOrderItemModel->actual_price,
                        'quantity' => $jer['quantity'],
                        'creator' => $oOrderItemModel->creator,
                        'create_time' => date('Y-m-d H:i:s'),
                        'wholesal_id' => $oOrderItemModel->wholesal_id,
                        'is_futures' => 0,
                        'pending_quantity' => $jer['quantity'],
                        'is_advance' => $oOrderItemModel->is_advance,
                        'advance_ratio' => $oOrderItemModel->advance_ratio,
                        'transaction_currency_id' => $oOrderItemModel->transaction_currency_id,
                        'price_selected_currency' => $oOrderItemModel->price_selected_currency,
                        'purchase_currency' => $inventory['purchase_currency'],
                        'purchase_price' => $inventory['purchase_price']
                    ]);
                    if (!$resultInsert) {
                        throw new Exception('订单转换库存插入订单明细失败');
                    }
                    $quantity = intval($jer['quantity']);
                    $resultUpdateInventory = InventoryModel::where('id', $inventory['id'])
                        ->whereRaw('available_qty - lock_qty >= ' . $quantity)
                        ->update([
                            'lock_qty' => Db::raw('lock_qty + ' . $quantity),
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                    if (!$resultUpdateInventory) {
                        throw new Exception('订单库存类型转换库存锁定失败');
                    }
                    $insert_param = [
                        'inventory_id' => $inventory['id'],
                        'business_tabel_name' => 'order',
                        'business_table_id' => $oOrderItemModel->order_id,
                        'business' => '库存锁定',
                        'remark' => '订单库存类型转换库存加锁',
                        'number' => $jer['quantity'],
                        'operator_id' => $param['operator_id'],
                    ];
                    $inventoryService->insertInventoryChanggeData($insert_param);

                    $unlock = $inventoryService->unlockInventory([[
                        'order_id' => $oOrderItemModel->order_id,
                        'product_id' => $oOrderItemModel->product_id,
                        'arrival_date' => $oOrderItemModel->arrival_date,
                        'is_futures' => $oOrderItemModel->is_futures,
                        'wid' => $oOrderItemModel->warehouse_id,
                        'quantity' => $jer['quantity'],
                        'operator_id' => $param['operator_id']
                    ]]);

                    if (!$unlock) {
                        throw new Exception('订单库存类型转换库存解锁失败');
                    }

                    $need_trans_quantity = $need_trans_quantity - $jer['quantity'];
                }
            }
            if ($need_trans_quantity > 0) {
                throw new Exception('库存不足');
            }

            $order = $oOrderItemModel->order_id; // 解除订单异常状态
            $order_item_exceptionstatus = Db::name('order_item')->where('order_id', $order)->whereNull('wholesal_id')->where('is_del', 0)->where('quantity', '>', 0)->where('pending_quantity', '>', 0)->where('exceptionstatus', 4)->select();

            if ($order_item_exceptionstatus->count() == 0) { // 如果订单明细没有异常状态为4的数据，则更新订单异常状态
                $order_exceptionstatus = Db::name('order')->where('id', $order)->field('id,exceptionstatus')->find();

                if ($order_exceptionstatus['exceptionstatus']) {
                    if (in_array(4, explode(',', $order_exceptionstatus['exceptionstatus']))) {
                        $order_exceptionstatus['exceptionstatus'] = implode(',', array_diff(explode(',', $order_exceptionstatus['exceptionstatus']), [4]));
                    }
                    Db::name('order')->where('id', $order)->update(['exceptionstatus' => $order_exceptionstatus['exceptionstatus']]);
                }
            }
            Db::commit();
            $orderInfo = Db::name('order')->where('id', $oOrderItemModel->order_id)->where('is_del',  0)->find();
            if (empty($oOrderItemModel->warehouse_code)) { // 订单自提
                $allOrderItem = OrderItemModel::where('order_id', $oOrderItemModel->order_id)->where('is_del',  0)->select(); // 全部订单明细

                $futures_num = 0;
                foreach ($allOrderItem as $item) {
                    if ($item->is_futures != 0) {
                        $futures_num += $item->quantity;
                    }
                }

                if ($futures_num == 0) {
                    $mailService = new Mail();
                    $orderInfo = Db::name('order')->where('id', $oOrderItemModel->order_id)->where('is_del',  0)->find();

                    $mailService->send('self_pickup', [
                        'user_id' => $orderInfo['user_id'],
                        'order_no' => $orderInfo['order_no'],
                    ]);
                }
            }
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 1, 'message' => $e->getMessage()];
        }
        return ['code' => 0, 'message' => '订单转换库存成功'];
    }

    public function transSaveByWholesal($param)
    {
        $oOrderItemModel = WholesalOrderItem::where('is_futures', '<>', 0)->find($param['id']);
        if (!$oOrderItemModel) {
            return ['code' => 1, 'message' => '未找到订单信息！'];
        }

        if (!empty($param['associated_delivery_order_ids'])) {
            $deliveryOrderProductNum = Db::name('order_item')
                ->whereIn('order_id', $param['associated_delivery_order_ids'])
                ->where('product_id', '=', $oOrderItemModel->product_id)
                ->where('arrival_date', '=', $oOrderItemModel->arrival_date)
                ->where('is_futures', '=', $oOrderItemModel->is_futures)
                ->where('warehouse_id', '=', $oOrderItemModel->warehouse_id)
                ->where('is_del', '=', 0)
                ->where('wholesal_id', '=', $oOrderItemModel->order_id)
                ->sum('pending_quantity'); // 选中发货订单中该商品数量
            $waiting_tran_quantity = array_sum(array_column($param['list'], 'quantity'));

            if ($deliveryOrderProductNum > $waiting_tran_quantity) {
                return ['code' => 1, 'message' => '选中发货订单中该商品数量大于库存类型转换数量！'];
            }
        }

        // 计算需要转换的总数量
        $need_trans_quantity = array_sum(array_column($param['list'], 'quantity'));

        // 查询可转换数量
        $where = [
            ['productid', '=', $param['productid']],
            ['arrival_date', '=', null],
            ['is_futures', '=', 0],
            ['is_del', '=', 0],
            ['id', 'in', array_column($param['list'], 'id')]
        ];

        $warehouse = DB::name('warehouse')->where('id', '=', $param['wid'])->field('fl_warehouse_id')->find();
        if ($warehouse['fl_warehouse_id'] != null) {
            $where[] = ['wid', '=', $param['wid']];
        } else {
            $warehouse_ids = DB::name('warehouse')->where('fl_warehouse_id', '=', $param['wid'])->column('id');
            $where[] = ['wid', 'in', $warehouse_ids];
        }

        $InventoryArr = DB::name('inventory')->where($where)
            ->whereRaw('(available_qty - lock_qty) > ?', [0])
            ->field(['available_qty - lock_qty as available_qty', 'id', 'purchase_currency', 'purchase_price',  'wid'])
            ->select()
            ->toArray(); // 查询可转换数量
        $InventoryArr = array_column($InventoryArr, null, 'id');
        $inventory_wid = array_unique(array_column($InventoryArr, 'wid'));
        if (count($inventory_wid) > 1) {
            throw new Exception('所选库存仓库ID 不一致');
        }
        $newOrderItemModel = new WholesalOrderItem();
        $inventoryService = new CommonInventoryService();

        Db::startTrans();
        try {

            $deliveryOrderProductNum = 0; // 相关发货订单数量 锁定数量也用这个
            if (!empty($param['associated_delivery_order_ids'])) { // 相关发货订单类型转换

                $this->handleDeliveryOrderTransSave($param['associated_delivery_order_ids'], $param['associated_delivery_order_items_ids'], $oOrderItemModel->toArray(), $inventory_wid[0]); // 处理相关发货订单
                $deliveryOrderProductNum = Db::name('order_item')->whereIn('order_id', $param['associated_delivery_order_ids'])->sum('pending_quantity');
            }

            foreach ($param['list'] as $jer) {

                $inventory = $InventoryArr[$jer['id']];

                if ($inventory['available_qty'] < $jer['quantity']) {
                    throw new Exception('库存不足');
                } else {

                    if ($deliveryOrderProductNum > 0) {
                        if ($deliveryOrderProductNum > $jer['quantity']) {
                            $lock_qty = $jer['quantity'];
                            $deliveryOrderProductNum = $deliveryOrderProductNum - $jer['quantity'];
                        } else {
                            $lock_qty = $deliveryOrderProductNum;
                            $deliveryOrderProductNum = 0;
                        }
                    } else {
                        $lock_qty = 0;
                    }
                    $quantity = intval($jer['quantity']);
                    $lock_qty = intval($lock_qty);
                    $resultUpdateOrderItem = $newOrderItemModel
                        ->where('id', $param['id'])
                        ->update([
                            'pending_quantity' => Db::raw('pending_quantity - ' . $quantity),
                            'quantity' => Db::raw('quantity - ' . $quantity),
                            'lock_qty' => Db::raw('lock_qty - ' . $lock_qty),
                        ]); // 原始订单明细减少
                    if (!$resultUpdateOrderItem) {
                        throw new Exception('订单转换原始明细数据扣减失败');
                    }
                    $resultInsert = $newOrderItemModel->insert([
                        'user_id' => $oOrderItemModel->user_id,
                        'order_id' => $oOrderItemModel->order_id,
                        'product_id' => $oOrderItemModel->product_id,
                        'warehouse_id' => $inventory['wid'],
                        'original_price' => $oOrderItemModel->original_price,
                        'actual_price' => $oOrderItemModel->actual_price,
                        'quantity' => $jer['quantity'],
                        'creator' => $oOrderItemModel->creator,
                        'create_time' => date('Y-m-d H:i:s'),
                        'is_futures' => 0,
                        'pending_quantity' => $jer['quantity'],
                        'lock_qty' => $lock_qty,
                        'is_advance' => $oOrderItemModel->is_advance,
                        'advance_ratio' => $oOrderItemModel->advance_ratio,
                        'transaction_currency_id' => $oOrderItemModel->transaction_currency_id,
                        'price_selected_currency' => $oOrderItemModel->price_selected_currency,
                        'purchase_currency' => $inventory['purchase_currency'],
                        'purchase_price' => $inventory['purchase_price'],
                        'free_shipping' => $oOrderItemModel->free_shipping,
                        'apply_rules' => $oOrderItemModel->apply_rules
                    ]);

                    if (!$resultInsert) {
                        throw new Exception('订单转换库存插入订单明细失败');
                    }
                    $quantity = intval($jer['quantity']);
                    $resultUpdateInventory = InventoryModel::where('id', $inventory['id'])
                        ->whereRaw('available_qty - lock_qty >= ' . $quantity)
                        ->update([
                            'lock_qty' => Db::raw('lock_qty + ' . $quantity),
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                    if (!$resultUpdateInventory) {
                        throw new Exception('订单库存类型转换库存锁定失败');
                    }

                    $insert_param = [
                        'inventory_id' => $inventory['id'],
                        'business_tabel_name' => 'order',
                        'business_table_id' => $oOrderItemModel->order_id,
                        'business' => '库存锁定',
                        'remark' => '经销商订单库存类型转换库存加锁',
                        'number' => $jer['quantity'],
                        'operator_id' => $param['operator_id'],
                    ];
                    $inventoryService->insertInventoryChanggeData($insert_param);

                    $unlock = $inventoryService->unlockInventory([[
                        'order_id' => $oOrderItemModel->order_id,
                        'product_id' => $oOrderItemModel->product_id,
                        'arrival_date' => $oOrderItemModel->arrival_date,
                        'is_futures' => $oOrderItemModel->is_futures,
                        'wid' => $oOrderItemModel->warehouse_id,
                        'quantity' => $jer['quantity'],
                        'operator_id' => $param['operator_id']
                    ]]);
                    if (!$unlock) {
                        throw new Exception('订单库存类型转换库存解锁失败');
                    }
                    $need_trans_quantity = $need_trans_quantity - $jer['quantity'];
                }
            }
            if ($need_trans_quantity > 0) {
                throw new Exception('库存不足');
            }


            $order = $oOrderItemModel->order_id; // 解除订单异常状态
            $order_item_exceptionstatus = Db::name('order_item')->where('order_id', $order)->whereNull('wholesal_id')->where('is_del', 0)->where('quantity', '>', 0)->where('pending_quantity', '>', 0)->where('exceptionstatus', 4)->select();

            if ($order_item_exceptionstatus->count() == 0) { // 如果订单明细没有异常状态为4的数据，则更新订单异常状态
                $order_exceptionstatus = Db::name('order')->where('id', $order)->field('id,exceptionstatus')->find();

                if ($order_exceptionstatus['exceptionstatus']) {
                    if (in_array(4, explode(',', $order_exceptionstatus['exceptionstatus']))) {
                        $order_exceptionstatus['exceptionstatus'] = implode(',', array_diff(explode(',', $order_exceptionstatus['exceptionstatus']), [4]));
                    }

                    Db::name('order')->where('id', $order)->update(['exceptionstatus' => $order_exceptionstatus['exceptionstatus']]);
                }
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return ['code' => 1, 'message' => $e->getMessage()];
        }
        return ['code' => 0, 'message' => '订单转换库存成功'];
    }
    /**
     * @describe 经销商资产订单转换，需要将关联的发货订单也转换为现货
     * @author: Bobo
     * @date: 2025-08-27 18:29:24 
     * @param [type] @required $associated_delivery_order_ids 关联的发货订单ID
     * @param [type] @required $associated_delivery_order_items_ids 关联的发货订单明细ID
     * @param [type] @required $oOrderItem 订单明细信息
     * @param [type] @required $warehouse_id 转入仓库ID
     * @param [type] @required $warehouse_id 转入仓库ID
     * @return Renderable
     */
    private function handleDeliveryOrderTransSave($associated_delivery_order_ids, $associated_delivery_order_items_ids, $oOrderItem, int $warehouse_id)
    {
        $associated_delivery_order_ids = array_unique($associated_delivery_order_ids);
        $order_list = Db::name('order')
            ->where('id', 'in', $associated_delivery_order_ids)
            ->field('id,exceptionstatus')
            ->select()
            ->toArray();
        if (empty($order_list)) {
            return;
        }

        foreach ($order_list as $item) { // 如果发货订单有异常状态，则需要将异常状态中的4去掉
            if ($item['exceptionstatus']) {
                $exceptionstatus = explode(',', $item['exceptionstatus']);
                if (in_array(4, $exceptionstatus)) {
                    $exceptionstatus = implode(',', array_diff($exceptionstatus, [4]));
                    Db::name('order')
                        ->where('id', '=', $item['id'])
                        ->update([
                            'exceptionstatus' => $exceptionstatus,
                        ]);
                }
            }
        }

        $result =  Db::name('order_item')
            // ->where('order_id', 'in', $associated_delivery_order_ids)
            ->where('id', 'in', $associated_delivery_order_items_ids)
            // ->where('product_id', '=', $oOrderItem['product_id'])
            // ->where('arrival_date', '=', $oOrderItem['arrival_date'])
            // ->where('is_futures', '=', $oOrderItem['is_futures'])
            // ->where('warehouse_id', '=', $oOrderItem['warehouse_id'])
            // ->where(function ($query) use ($oOrderItem) {
            //     if ($oOrderItem['wholesal_id'] > 0) {
            //         $query->where('wholesal_id', '=', $oOrderItem['wholesal_id']);
            //     }
            // })
            // ->where('is_del', '=', 0)
            // ->where('quantity', '>', 0)
            ->update([
                'is_futures' => 0,
                'arrival_date' => null,
                'real_arrival_date' => null,
                'warehouse_id' => $warehouse_id,
                'exceptionstatus' => Db::raw('CASE WHEN exceptionstatus = "4" THEN NULL ELSE exceptionstatus END'),
            ]);

        if (!$result) {
            throw new Exception('处理相关发货订单失败');
        }
    }

    public function transSave($param)
    {

        $order_id_arr = [];
        if (!empty($param['list'])) {
            $order_id_arr = array_column($param['list'], 'id');
        }
        $where = [['is_del', '=', '0'], ['id', '=', $param['id']]];
        $oInventoryModel = InventoryModel::where($where)->find();
        $original_is_futures = $oInventoryModel->is_futures;
        $original_wid = $oInventoryModel->wid;
        if (!$oInventoryModel) {
            return ['code' => 1, 'message' => '未找到库存信息！！'];
        }
        if ($oInventoryModel->is_futures <= $param['futures']) {
            return ['code' => 1, 'message' => '转换类型错误！'];
        }
        if ($oInventoryModel->convertible_qty < $param['convertible_qty']) {
            return ['code' => 1, 'message' => '可转换数量不足！'];
        }
        $warehouseArr = [$param['intoWarehouse'], ...explode(',', $oInventoryModel->wid)];

        $order_where = [
            ['product_id', '=', $oInventoryModel->productid],
            ['warehouse_id', 'in', $warehouseArr],
            ['arrival_date', '=', $oInventoryModel->arrival_date],
            ['is_futures', '=', $oInventoryModel->is_futures]
        ];

        $order_sum = 0;
        if (!empty($order_id_arr)) {
            $order_sum = Db::table('db_order_item')
                ->alias('item')
                ->leftJoin('db_order o', 'o.id = item.order_id')
                ->where($order_where)
                ->whereIn('o.id', $order_id_arr)
                ->sum('item.quantity');
        }
        if (($order_sum) > $param['convertible_qty']) {
            return ['code' => 1, 'message' => '转换数量小于关联订单数量！'];
        }

        Db::startTrans();
        try {

            // 插入新数据
            $newInventoryModel = new InventoryModel();
            $newInventoryModel->productid = $oInventoryModel->productid;
            $newInventoryModel->wid = $param['intoWarehouse'] ?? $oInventoryModel->wid;
            $newInventoryModel->source_table = 'inventory';
            $newInventoryModel->source_id = $oInventoryModel->id;
            $newInventoryModel->initial_qty = $param['convertible_qty'];
            $newInventoryModel->convertible_qty = $param['futures'] == 0 ? 0 : $param['convertible_qty'];
            $newInventoryModel->available_qty = $param['convertible_qty'];

            /* 继承原来 allow_zero_stock_sale */
            $newInventoryModel->allow_zero_stock_sale = $oInventoryModel->allow_zero_stock_sale;

            $newInventoryModel->lock_qty = 0;
            $newInventoryModel->is_sale = $oInventoryModel->is_sale;
            $newInventoryModel->arrival_date = $param['arrival_date'] ?? null;
            $newInventoryModel->real_arrival_date = $param['arrival_date'] ?? null;
            $newInventoryModel->inbound_batch = $param['arrival_batch'];
            $newInventoryModel->is_futures = $param['futures'];
            $newInventoryModel->remark = $oInventoryModel->remark;
            $newInventoryModel->last_audit_date = $oInventoryModel->last_audit_date;
            $newInventoryModel->is_del = 0;
            $newInventoryModel->creator = $param['operator_id'];
            $newInventoryModel->create_time = date('Y-m-d H:i:s');
            $newInventoryModel->purchase_currency = $oInventoryModel->purchase_currency;
            $newInventoryModel->purchase_price = $oInventoryModel->purchase_price;

            $warehouse = Db::name('warehouse')->where('id', $newInventoryModel->wid)->find();
            if ($warehouse) {
                if ($warehouse['fl_warehouse_id']) {
                    $ccname_ids = Db::name('cc_names')->where('is_del', 0)->whereRaw('FIND_IN_SET(?, sellable_wids)', [$warehouse['fl_warehouse_id']])->column('id');
                } else {
                    $ccname_ids = Db::name('cc_names')->where('is_del', 0)->whereRaw('FIND_IN_SET(?, sellable_wids)', [$newInventoryModel->wid])->column('id');
                }
            }
            $newInventoryModel->ccname_ids = $ccname_ids ? implode(',', $ccname_ids) : null;


            /* 批量修改类型 是否可零库存售卖保持一致 start */
            $newAllowZeroStockSale[] = ['productid', '=', $newInventoryModel->productid];
            $newAllowZeroStockSale[] = ['wid', '=', $newInventoryModel->wid];
            $newAllowZeroStockSale[] = ['arrival_date', '=', $newInventoryModel->arrival_date];
            $newAllowZeroStockSale[] = ['is_futures', '=', $newInventoryModel->is_futures];
            InventoryModel::where($newAllowZeroStockSale)->update([
                'allow_zero_stock_sale' => $newInventoryModel->allow_zero_stock_sale,
                'update_time' => date('Y-m-d H:i:s', time()),
                'updater' => $param['operator_id']
            ]);
            /* 批量修改类型 是否可零库存售卖保持一致 end */

            if (!$newInventoryModel->save()) {
                throw new Exception("库存转换失败！");
            }

            /* 维护库存盘点数据 start */
            $exists = Db::name('product_sold_stat')
                ->where('productid', $oInventoryModel->productid)
                ->where('warehouse_id', $param['intoWarehouse'] ?? $oInventoryModel->wid)
                ->find();

            if ($exists) {
                // 数据存在，更新数量
                Db::name('product_sold_stat')
                    ->where('productid', $oInventoryModel->productid)
                    ->where('warehouse_id', $param['intoWarehouse'] ?? $oInventoryModel->wid)
                    ->bind([
                        'inc_num' => intval($param['convertible_qty'])
                    ])
                    ->update([
                        'available_qty' =>  Db::raw('available_qty - :inc_num'),
                        'update_time' => date('Y-m-d H:i:s')
                    ]);
            } else {
                // 数据不存在，插入新数据
                Db::name('product_sold_stat')->insert([
                    'productid' => $oInventoryModel->productid,
                    'warehouse_id' =>  $param['intoWarehouse'] ?? $oInventoryModel->wid,
                    'available_qty' => $param['convertible_qty'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'update_time' => date('Y-m-d H:i:s')
                ]);
            }
            /* 维护库存盘点数据 end */


            // 更新新库存的价格
            $discount_insert = [];
            if (isset($param['intoWarehouse']) && $param['intoWarehouse']) {
                $partent_wid  = Db::name('warehouse')->where('id', $param['intoWarehouse'])->value('fl_warehouse_id');
            } else {
                $partent_wid  = $oInventoryModel->wid;
            }
            // 获取原有价格
            $oProductPriceModel = ProductPriceModel::with('discount')->where([
                ['inventory_id', '=', $oInventoryModel->id],
                ['wid', '=', $partent_wid],
                ['is_del', '=', '0']
            ])->select();


            foreach ($oProductPriceModel as $item) {
                $newProductPriceModel = new ProductPriceModel();
                $newProductPriceModel->inventory_id = $newInventoryModel->id;
                $newProductPriceModel->wid = $newInventoryModel->wid;
                $newProductPriceModel->transaction_currency_id = $item->transaction_currency_id;
                $newProductPriceModel->price = $item->price;
                $newProductPriceModel->first_leg_logistics_fee = $item->first_leg_logistics_fee;
                $newProductPriceModel->is_del = 0;
                $newProductPriceModel->creator = $param['operator_id'];
                $newProductPriceModel->create_time = date('Y-m-d H:i:s');
                if (!$newProductPriceModel->save()) {
                    throw new Exception("库存价格存储失败！");
                }
                if ($item->discount) {
                    foreach ($item->discount as $discount) {
                        $discount_insert[] = [
                            'price_id' => $newProductPriceModel->id,
                            'level' => $discount->level,
                            'num' => $discount->num,
                            'rate' => $discount->rate,
                            'price' => $discount->price,
                            'creator' => $param['operator_id'],
                            'create_time' => date('Y-m-d H:i:s')
                        ];
                    }
                }
            }

            if (count($discount_insert) > 0) {
                $discount_result = ProductDiscountModel::insertAll($discount_insert);
                if (!$discount_result) {
                    throw new Exception("库存折扣存储失败！");
                }
            }
            $old_convertible_qty  = $oInventoryModel->convertible_qty - $param['convertible_qty'];
            // 更新原数据

            $update_i = Inventory::where('id',$oInventoryModel->id)->where('convertible_qty','>=',$param['convertible_qty'])->dec('initial_qty',$param['convertible_qty'])
                ->dec('convertible_qty',$param['convertible_qty'])
                ->dec('available_qty',$param['convertible_qty'])
                ->update();

            if ($old_convertible_qty == 0) { //可转数量为零的时候 可售关闭
                $oInventoryModel->is_sale = 0;
                #调拨单判断是否全部转换完成
               $logistics_order_id =  LogisticsOrderItem::where('to_inventory_id',$oInventoryModel->id)->value('logistics_order_id');
               $to_inventory_ids =  LogisticsOrderItem::where('logistics_order_id',$logistics_order_id)->column('to_inventory_id');
               $inventorys = Inventory::whereIn('id',$to_inventory_ids)->select()->toArray();
               $sum_convertible_qty = array_sum(array_column($inventorys,'convertible_qty'));
               if( $sum_convertible_qty == 0){
                   $result =  \app\admin\model\LogisticsOrder::where('id', $logistics_order_id)->update(['status' => 3]);
                   if(!$result){
                       Log::error('调拨单入库状态更新失败');
                   }
               }

            }
            if (!$update_i) {
                throw new Exception("更新库存数据失败！");
            }

            // 处理关联订单明细类型转换
            $this->handleOrderTypeTransSave($param['list'], $order_where, $newInventoryModel, $param['operator_id']);


            $handleRemainingRelatedOrderAreAbnormalParams = [
                'id' => $param['id'],
                'currentWId' => $original_wid,
                'operator_id' => $param['operator_id']
            ];
            if ($original_is_futures == 2) {
                $handleRelatedOrderAreAbnormalParams['transferInWId'] = $param['intoWarehouse'];
            }
            // 处理剩余关联订单是否异常
            $handleRemainingRelatedOrderAreAbnormal = $this->handleRemainingRelatedOrderAreAbnormal($handleRemainingRelatedOrderAreAbnormalParams, $old_convertible_qty);
            if (!$handleRemainingRelatedOrderAreAbnormal) {
                throw new Exception('处理关联订单异常失败');
            }

            DB::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('库存转换失败:file:' . $e->getFile() . ' line:' . $e->getLine() . ' message:' . $e->getMessage());
            return ['code' => 1, 'message' => 'line.' . $e->getLine() . ' ' . $e->getMessage()];
        }
        return ['code' => 0, 'message' => '转换成功！', 'data' => $newInventoryModel->id];
    }

    /**
     * @describe 处理关联订单明细类型转换
     * @author: Bobo
     * @date: 2025-08-29 18:04:28 
     * @param [type] @required
     * @return Renderable
     */
    private function handleOrderTypeTransSave($param_list, $order_where, $newInventoryModel, $operator_id)
    {
        $log = '库存类型转换处理关联订单明细:';
        foreach ($param_list as $item) { // 处理关联订单明细
            // 更新原子订单关联库存信息
            $oldOrderItem = OrderItem::hasWhere('orders')->where($order_where)->where('order_id', $item['id'])->select();

            $tempItem = $oldOrderItem->toArray()[0];

            if (!$oldOrderItem) {
                throw new Exception("未找到相关子订单数据！");
            }
            $order = Db::name('order')->where('id', $item['id'])->find();
            if ($order['exceptionstatus']) {
                $order_exceptionstatus = explode(',', $order['exceptionstatus']);
                $order_exceptionstatus = array_filter($order_exceptionstatus, function ($value) {
                    return $value != 4;
                });
                $order['exceptionstatus'] = implode(',', $order_exceptionstatus);
                Db::name('order')->where('id', $item['id'])->update(['exceptionstatus' => $order['exceptionstatus']]); // 清除原订单批次异常状态
                $log .= '原订单批次可转数量不足异常状态清除:id:' . $item['id'] . "\n";
            }

            $wholesal_delivery_order_items_list = Db::name('order_item')
                ->where('wholesal_id', $item['id'])
                ->where('arrival_date', $tempItem['arrival_date'])
                ->where('is_futures', $tempItem['is_futures'])
                ->where('warehouse_id', $tempItem['warehouse_id'])
                ->where('product_id', $tempItem['product_id'])
                ->where('is_del', 0)
                ->field('id,order_id')
                ->select()
                ->toArray(); // 获取发货订单明细

            if ($wholesal_delivery_order_items_list) {
                $wholesal_delivery_order_items_ids = array_column($wholesal_delivery_order_items_list, 'id');
                $wholesal_delivery_order_items_order_ids = array_unique(array_column($wholesal_delivery_order_items_list, 'order_id'));
                $wholesal_delivery_order_items_update = Db::name('order_item')
                    ->whereIn('id', $wholesal_delivery_order_items_ids)
                    ->update([
                        'exceptionstatus' => Db::raw('CASE WHEN exceptionstatus = "4" THEN NULL ELSE exceptionstatus END'),
                        'is_futures' =>  $newInventoryModel->is_futures,
                        'arrival_date' =>  $newInventoryModel->arrival_date,
                        'real_arrival_date' =>  $newInventoryModel->arrival_date,
                        'warehouse_id' =>   $param['intoWarehouse'] ?? $newInventoryModel->wid,
                    ]); // 发货订单明细批次异常清除 并且修改类型 仓库 期货类型 到货日期
                $log .= '关联发货订单明细批次异常状态清除,修改类型 仓库 期货类型 到货日期:id:' . implode(',', $wholesal_delivery_order_items_ids) . "\n";
                foreach ($wholesal_delivery_order_items_order_ids as $wholesal_delivery_order_items_order_id) {
                    $wholesal_delivery_order_exceptionstatus = Db::name('order')
                        ->where('id', $wholesal_delivery_order_items_order_id)
                        ->value('exceptionstatus');
                    if ($wholesal_delivery_order_exceptionstatus) {
                        $wholesal_delivery_order_exceptionstatus = explode(',', $wholesal_delivery_order_exceptionstatus);
                        $wholesal_delivery_order_exceptionstatus = array_filter($wholesal_delivery_order_exceptionstatus, function ($value) {
                            return $value != 4;
                        });
                        $wholesal_delivery_order_exceptionstatus = implode(',', $wholesal_delivery_order_exceptionstatus);
                        Db::name('order')->where('id', $wholesal_delivery_order_items_order_id)->update(['exceptionstatus' => $wholesal_delivery_order_exceptionstatus]); // 发货订单批次异常清除
                        $log .= '关联发货订单批次异常状态清除:id:' . $wholesal_delivery_order_items_order_id . "\n";
                    }
                }
            }

            $resultUpdateOrderItem = OrderItem::hasWhere('orders')->where($order_where)->where('OrderItem.order_id', $item['id'])->update(['OrderItem.is_del' => time()]); // 逻辑删除所有老数据
            $log .= '逻辑删除所有老数据:id:' . $item['id'] . "\n";
            if (!$resultUpdateOrderItem) {
                throw new Exception('删除订单明细数据失败');
            }


            $insert = [
                'user_id' => $tempItem['user_id'],
                'order_id' => $item['id'],
                'product_id' => $tempItem['product_id'],
                'quantity' => $item['num'],
                'warehouse_id' => $param['intoWarehouse'] ?? $newInventoryModel->wid,
                'original_price' =>  $tempItem['original_price'],
                'actual_price' =>  $tempItem['actual_price'],
                'creator' =>  $newInventoryModel->creator,
                'create_time' => date('Y-m-d H:i:s', time()),
                'arrival_date' => $newInventoryModel->arrival_date,
                'is_futures' =>  $newInventoryModel->is_futures,
                'pending_quantity' => $item['num'],
                'lock_qty' => $tempItem['lock_qty'],
                'is_advance' =>  $tempItem['is_advance'],
                'advance_ratio' =>  $tempItem['advance_ratio'],
                'transaction_currency_id' =>  $tempItem['transaction_currency_id'],
                'price_selected_currency' =>  $tempItem['price_selected_currency'],
                'purchase_currency' =>  $newInventoryModel->purchase_currency,
                'purchase_price' =>  $newInventoryModel->purchase_price,
                'free_shipping' =>  $tempItem['free_shipping'],
                'apply_rules' =>  $tempItem['apply_rules'],
            ];
            $log .= '新增订单明细数据:id:' . $item['id'] . "\n";
            if (!OrderItem::insert($insert)) {
                throw new Exception("新增订单明细数据失败！");
            }
            // 扣除新创建库存数据的锁定数量
            $newInventoryModel->lock_qty = $newInventoryModel->lock_qty + $item['num'];
            if (!$newInventoryModel->save()) {
                throw new Exception("更新库存数据失败！");
            }
            $log .= '更新库存锁定数据:id:' . $newInventoryModel->id . ",lock_qty:" . $newInventoryModel->lock_qty . "\n";
            $insert_param = [
                'inventory_id' => $newInventoryModel->id,
                'business_tabel_name' => 'order',
                'business_table_id' => $item['id'],
                'business' => '库存锁定',
                'remark' => '订单库存类型转换库存加锁',
                'number' => $item['num'],
                'operator_id' => $operator_id,
            ];
            $commonInventoryService = new CommonInventoryService();
            $commonInventoryService->insertInventoryChanggeData($insert_param);
            if ($tempItem['exceptionstatus'] != 4) { // 如果原订单明细异常状态不是4，则解锁库存

                $unlock = $commonInventoryService->unlockInventory([[
                    'order_id' => $item['id'],
                    'product_id' => $tempItem['product_id'],
                    'arrival_date' => $tempItem['arrival_date'],
                    'is_futures' => $tempItem['is_futures'],
                    'wid' => $tempItem['warehouse_id'],
                    'quantity' => $item['num'],
                    'operator_id' => $operator_id
                ]]);
                if (!$unlock) {
                    throw new Exception('库存类型转换原订单明细库存解锁失败');
                }
                $log .= '库存类型转换原订单明细库存解锁:id:' . $item['id'] . ",num:" . $item['num'] . "\n";
            }
        }
        Log::info($log);
    }
    /**
     * @describe 处理剩余关联订单是否异常
     * @author: Bobo
     * @date: 2025-08-26 18:06:14 
     * @param [type]
     * @return Renderable
     */
    private function handleRemainingRelatedOrderAreAbnormal($param, $remaining_convertible_qty)
    {

        $order_result = $this->getOrderByInventory($param);


        if ($order_result['code'] == 0) {
            $order_data = $order_result['data'];
            $total_num =  array_sum(array_column($order_data, 'num'));

            if ($total_num > $remaining_convertible_qty) {  // 如果剩余待转订单总数量大于剩余期货可转数量，则订单全部标记异常
                try {
                    $log = '库存转换处理剩余未转数量大于剩余期货可转数量，剩余未转订单全部标记异常' . "\n";
                    Db::startTrans();
                    foreach ($order_data as $item) {

                        $order_item_update = Db::name('order_item')
                            ->where('order_id', $item['order_id'])
                            ->whereIn('id', $item['order_item_ids'])
                            ->update(['exceptionstatus' =>  4]); // 订单明细异常

                        $log .= '订单明细异常更新:id:' . $item['order_item_ids'] . ',order_id:' . $item['order_id'] . "\n";

                        $order_update = Db::name('order')
                            ->where('id', $item['order_id'])
                            ->update(['exceptionstatus' => Db::raw('CASE WHEN exceptionstatus IS NULL OR exceptionstatus = "" THEN "4" ELSE CONCAT(exceptionstatus, ",4") END'), 'update_time' => date('Y-m-d H:i:s', time()), 'updater' => $param['operator_id']]); // 订单异常
                        $log .= '订单异常更新:id:' . $item['order_id'] . "\n";

                        if ($item['order_type'] == 'wholesal') { // 如果是经销商订单,除了订单本身，相关的发货订单也需要异常
                            $wholesal_delivery_order_items_list = Db::name('order_item')
                                ->where('wholesal_id', $item['order_id'])
                                ->where('arrival_date', $item['arrival_date'])
                                ->where('is_futures', $item['is_futures_value'])
                                ->where('warehouse_id', $item['warehouse_id'])
                                ->where('product_id', $item['product_id'])
                                ->where('pending_quantity', '>', 0)
                                ->where('is_del', 0)
                                ->field('id,order_id')
                                ->select()
                                ->toArray();


                            if ($wholesal_delivery_order_items_list) { // 如果发货订单明细存在，则更新发货订单明细和发货订单异常
                                $wholesal_delivery_order_items_ids = array_column($wholesal_delivery_order_items_list, 'id');
                                $wholesal_delivery_order_items_order_ids = array_unique(array_column($wholesal_delivery_order_items_list, 'order_id'));

                                $wholesal_delivery_order_items_update = Db::name('order_item')
                                    ->whereIn('id', $wholesal_delivery_order_items_ids)
                                    ->update(['exceptionstatus' =>  4]); // 发货订单明细异常状态添加

                                $log .= '发货订单明细异常更新:id:' . implode(',', $wholesal_delivery_order_items_ids) . "\n";

                                foreach ($wholesal_delivery_order_items_order_ids as $wholesal_delivery_order_items_order_id) {


                                    $wholesal_delivery_order_exceptionstatus = Db::name('order')
                                        ->where('id', $wholesal_delivery_order_items_order_id)
                                        ->value('exceptionstatus');



                                    if ($wholesal_delivery_order_exceptionstatus) {
                                        $wholesal_delivery_order_exceptionstatus = explode(',', $wholesal_delivery_order_exceptionstatus);
                                        $wholesal_delivery_order_exceptionstatus = array_unique(array_merge($wholesal_delivery_order_exceptionstatus, [4]));
                                        $wholesal_delivery_order_exceptionstatus = implode(',', $wholesal_delivery_order_exceptionstatus);

                                        Db::name('order')->where('id', $wholesal_delivery_order_items_order_id)->update(['exceptionstatus' => $wholesal_delivery_order_exceptionstatus, 'update_time' => date('Y-m-d H:i:s', time()), 'updater' => $param['operator_id']]); // 发货订单批次异常添加
                                    } else {
                                        Db::name('order')->where('id', $wholesal_delivery_order_items_order_id)->update(['exceptionstatus' => '4', 'update_time' => date('Y-m-d H:i:s', time()), 'updater' => $param['operator_id']]); // 发货订单批次异常添加
                                    }
                                    $log .= '发货订单异常更新:id:' . $wholesal_delivery_order_items_order_id . "\n";
                                }
                            }
                        }
                    }
                    Log::info($log);
                    Db::commit();
                    return true;
                } catch (\Throwable $th) {
                    Db::rollback();
                    Log::error('库存转换处理关联订单异常失败:file:' . $th->getFile() . ' line:' . $th->getLine() . ' message:' . $th->getMessage());
                    return false;
                }
            }
        }
        return true;
    }
}
